library(haven)
library(ggplot2)
library(tidyr)
library(dplyr)
library(stringr)

setwd("C:/Users/jonves/Dropbox/Papers/SSP-Instability-Opinion/replication_data/")

growth <- function(x){x/lag(x)-1}

pwt <- read_dta("data/pwt90.dta")
pwt2gwno <- read.csv("data/pwt2gwno.csv", stringsAsFactors = FALSE, strip.white = TRUE)

pwt <- pwt[which(!is.na(pwt$rgdpna)),]

# Each country start at a different year
#View(group_by(df, countrycode) %>% summarise(min(year)))

source("code/brd_old.R")


ucdpyearly <- merge(ucdpyearly, pwt2gwno, by.x="GWNoBattle", by.y="gwno")
df <- merge(pwt, ucdpyearly, by.x=c("country", "year"), by.y=c("country", "Year"), all.x=TRUE)

df$BdBest <- if_else(is.na(df$BdBest), 0, df$BdBest)

df <- group_by(df, countrycode) %>%
  mutate(grwt = growth(rgdpna/pop),
         Bdpop = (BdBest/pop),
         numyears = n(),) %>%
  select(countrycode, year, grwt, Bdpop, numyears) %>%
  filter(min(numyears)>=25) %>% # Minimum 25 years with observations (dropping Curacao and Sint Maarten)
  summarise(neggrwt = mean(grwt<0, na.rm=T),
            aBdpop = mean(Bdpop, na.rm=T))



p2 <- ggplot(df, aes(x=aBdpop+1, y=neggrwt)) + geom_point() + 
  geom_smooth(method="lm", se=FALSE, color="red") +
  xlab("Log average battle deaths per million pop. per year") + 
  ylab("Share of years with negative growth (PWT 9.0, 1950-2014)") +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
  scale_x_log10(breaks=c(10, 100, 1000)) + 
  theme_bw() +
  theme(strip.text.x = element_text(size=14),
        axis.title = element_text(size=14),
        axis.text = element_text(size=14))

ggsave("results/figure4c.tiff", plot=p2, width=6, height=6, dpi=300, compression="zip")